package com.newer.service.sys.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.fabric.xmlrpc.base.Array;
import com.newer.dao.sys.mapper.OrganizationMapper;
import com.newer.dao.sys.mapper.RoleMapper;
import com.newer.dao.sys.mapper.UserMapper;
import com.newer.dao.sys.mapper.UserRoleMapper;
import com.newer.pojo.sys.Organization;
import com.newer.pojo.sys.OrganizationExample;
import com.newer.pojo.sys.Role;
import com.newer.pojo.sys.RoleExample;
import com.newer.pojo.sys.User;
import com.newer.pojo.sys.UserExample;
import com.newer.pojo.sys.UserRole;
import com.newer.pojo.sys.UserRoleExample;
import com.newer.service.sys.iter.UserService;
import com.newer.utils.sys.BootstrapDataTable;
import com.newer.utils.sys.Conditions;
import com.newer.utils.sys.IsNotNullUtil;
import com.newer.utils.sys.MsgUtil;
import com.newer.utils.sys.SuggestUtil;
/**
 * 业务层
 * @author wo
 *
 */

@Service("userService")
public class UserServiceImpl implements UserService{

	@Autowired
	private  UserMapper userMapper;

	@Autowired
	private  RoleMapper roleMapper;

	@Autowired
	private  UserRoleMapper userRoleMapper;

	@Autowired
	private  OrganizationMapper organizationMapper;

	/**
	 * 添加用户
	 */
	@Override
	public int add(User user) {
		//设置为删除状态为未删除
		user.setDeleteStatus(0);
		//设置创建时间为系统当前时间
		user.setCreateDate(new Date());
		//md5加密
		user.setPassword(new SimpleHash("Md5", user.getPassword(),user.getUserName(),6).toString());
		return userMapper.insert(user);
	}

	/**
	 * 修改用户
	 */
	public int updateUser(User user) {
		int i = userMapper.updateByPrimaryKeySelective(user);
		if (i>0) {
			//先删除关联表的数据
			UserRoleExample example=new UserRoleExample();
			example.createCriteria().andUserIdEqualTo(user.getId());
			userRoleMapper.deleteByExample(example);
			if (IsNotNullUtil.isNotNull(user.getRoleIds())) {
				String[] ids=user.getRoleIds().split(",");
				UserRole userRole=new UserRole();
				if (IsNotNullUtil.isNotNull(ids)) {
					for (String id : ids) {
						userRole.setUserId(user.getId());
						userRole.setRoleId(Integer.parseInt(id));
						userRoleMapper.insert(userRole);
					}
				}
			}
		}

		return i;
	}

	/**
	 * 假删除，实际修改状态
	 */
	public  int deleteUser(User user){
		UserRoleExample example=new UserRoleExample();
		//实例化传参对象
		User users = new User();
		//设置值
		users.setId(user.getId());
		users.setDeleteStatus(1);//设置删除状态为1
		int i = userMapper.updateByPrimaryKeySelective(users);
		if (i>0) {
			example.createCriteria().andUserIdEqualTo(user.getId());
		}
		return userRoleMapper.deleteByExample(example);
	}


	/**
	 * 查询所有的用户，状态为0
	 */
	@Override
	public BootstrapDataTable tableView(BootstrapDataTable dataTable,Conditions conditions) {
		UserExample example=new UserExample();

		//设置排序条件
		if (IsNotNullUtil.isNotNull(dataTable.getSort())&&IsNotNullUtil.isNotNull(dataTable.getOrder())) {
			example.setOrderByClause(dataTable.getSort()+" "+dataTable.getOrder());
		}

		//设置查询条件
		if (IsNotNullUtil.isNotNull(conditions.getRealName())) {
			example.createCriteria().andRealNameLike("%"+conditions.getRealName()+"%");
		}
		//查询未删除的记录
		example.createCriteria().andDeleteStatusEqualTo(0);
		//设置分页条件
		
		PageHelper.offsetPage(dataTable.getOffset(), dataTable.getLimit());

		List<User> list = userMapper.selectByExample(example);

		PageInfo<User> info=new PageInfo<User>(list);
		//设置值
		dataTable.setRows(info.getList());
		//dataTable.setLimit(info.getPageSize());
		dataTable.setTotal(new Long(info.getTotal()).intValue());
		return dataTable;

	}


	/**
	 * 查询所有的角色
	 */
	@Override
	public List<Role> seleteRole(RoleExample example) {
		//查询未删除的记录
		example.createCriteria().andDeleteStatusEqualTo(0);
		return roleMapper.selectByExample(example);
	}

	/**
	 * 根据用户id查询他所具有的角色信息
	 */
	public List<UserRole> selectUserRoles(Integer userId) {
		UserRoleExample example=new UserRoleExample();
		example.createCriteria().andUserIdEqualTo(userId);
		return userRoleMapper.selectByExample(example);
	}

	/**
	 * 查询所有的组织
	 */
	@Override
	public List<Organization> seleteOrganization(OrganizationExample example) {
		//查询未删除的记录
		return organizationMapper.selectByExample(example);
	}

	/**
	 * 检查用户名是否重复
	 */
	@Override
	public Map<String, Boolean> seleclUserByUserName(String userName) {
		//实例化map
		Map<String, Boolean> resultMap = new HashMap<String, Boolean>();
		// 设置结果值
		boolean result = true;
		//查询角色
		User user = userMapper.selectByName(userName);
		//判断对象是否为空      查到返回false否则true
		if(user!=null) {
			result = false;//查到返回false
		}
		//设置返回结果
		resultMap.put("valid", result);
		//返回结果
		return resultMap;
	}

	/**
	 * 检查用户名是否重复
	 */
	@Override
	public Map<String, Boolean> seleclUserByTelephone(String telephone,Integer id) {
		//实例化map
		Map<String, Boolean> resultMap = new HashMap<String, Boolean>();
		// 设置结果值
		boolean result = true;
		if (IsNotNullUtil.isNotNull(id)) {
			User user = userMapper.selectByPrimaryKey(id);
			if (telephone.equals(user.getTelephone())) {
				resultMap.put("valid", result);
				return resultMap;
			}
		}
		//查询角色
		User user = userMapper.selectByTelephone(telephone);
		//判断对象是否为空      查到返回false否则true
		if(user!=null) {
			result = false;//查到返回false
		}
		//设置返回结果
		resultMap.put("valid", result);
		//返回结果
		return resultMap;
	}

	/**
	 * 修改密码
	 */
	public int updatePassword(String password,String newPassword,Integer id) {
		return userMapper.updatePassword(password,newPassword, id);
	}


	/**
	 * 批量删除
	 */
	@Override
	public int deleteUserByIds(String Ids) {
		//分割
		String[] split=Ids.split(",");
		//声明集合对象
		List<String> ids=null;
		if (IsNotNullUtil.isNotNull(split)) {
			ids=new  ArrayList<String>();
			for (String id : split) {
				ids.add(id);
			}
		}

		return userMapper.deleteByIds(ids);
	};






	@Override
	public int countByExample(UserExample example) {
		// TODO Auto-generated method stub
		return userMapper.countByExample(example);
	}

	@Override
	public int deleteByExample(UserExample example) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int deleteByPrimaryKey(Integer userid) {
		// TODO Auto-generated method stub
		return userMapper.deleteByPrimaryKey(userid);
	}

	@Override
	public int insert(User record) {
		// TODO Auto-generated method stub
		return userMapper.insert(record);
	}

	@Override
	public int insertSelective(User record) {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public User selectByPrimaryKey(Integer userid) {
		// TODO Auto-generated method stub
		return userMapper.selectByPrimaryKey(userid);
	}

	@Override
	public int updateByExampleSelective(User record, UserExample example) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updateByExample(User record, UserExample example) {
		// TODO Auto-generated method stub
		return userMapper.updateByExample(record, example);
	}

	@Override
	public int updateByPrimaryKeySelective(User record) {
		// TODO Auto-generated method stub
		return userMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(User record) {
		// TODO Auto-generated method stub
		return userMapper.updateByPrimaryKey(record);

	}

	@Override
	public SuggestUtil selectSuggest(Conditions conditions) {
		SuggestUtil util=new SuggestUtil();
		List<User> list = userMapper.selectByExample(null);
		util.setCode(200);
		util.setValue(list);
		return util;
	}

	@Override
	public User getByUserName(String principal) {
		User user = userMapper.selectByName(principal);
		return user;
	}













}
